import { NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

/**
 * @swagger
 * /api/regions/{id}:
 *   put:
 *     summary: 更新行政区划
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *     requestBody:
 *       content:
 *         application/json:
 *           example:
 *             name: "北京市"
 *             orderNum: 1
 *   delete:
 *     summary: 删除行政区划
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 */

export async function PUT(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json()

    // 检查是否存在子区划
    if (body.code) {
      const hasChildren = await prisma.region.findFirst({
        where: { parentCode: body.code }
      })
      if (hasChildren) {
        return NextResponse.json(
          { error: '该区划存在下级区划，无法修改区划代码' },
          { status: 400 }
        )
      }
    }

    const region = await prisma.region.update({
      where: { id: params.id },
      data: {
        name: body.name,
        code: body.code,
        level: body.level,
        parentCode: body.parentCode,
        orderNum: body.orderNum,
        status: body.status
      }
    })
    
    return NextResponse.json(region)
  } catch (error) {
    console.error('更新行政区划失败:', error)
    return NextResponse.json(
      { error: '更新行政区划失败' },
      { status: 500 }
    )
  }
} 